from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password
from myApp.models import User, LoginRecord
from django.contrib.auth import authenticate, login, logout
from .models import BossInfo, JobInfo
import json
import ast
from rest_framework import viewsets
from .serializers import ItemSerializer


# Create your views here.
# 登录
def login_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 验证用户
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)    # 登录
            last_login_ip = request.META['REMOTE_ADDR']     # 获取用户IP

            # 创建登录记录
            LoginRecord.objects.create(user=user, last_login_ip=last_login_ip)
            return redirect('index')
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误，请稍后再试。'})

    return render(request, 'login.html')


def userinfo_view(request):
    return render(request, 'userinfo.html')


# 注册
def register_view(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')

        # 验证用户名是否已存在
        try:
            User.objects.get(username=username)
            return render(request, 'register.html', {'error': '用户已存在'})
        except User.DoesNotExist:
            User.objects.create(username=username, email=email, password=make_password(password))
            return redirect('login')

    return render(request, 'register.html')


# 检查用户名
def check_username(request):
    username = request.GET.get('username')
    # 1==存在，0==不存在
    try:
        User.objects.get(username=username)
        return JsonResponse({'status': 1})
    except User.DoesNotExist:
        return JsonResponse({'status': 0})


# 检查邮箱
def check_email(request):
    email = request.GET.get('email')
    try:
        User.objects.get(email=email)
        return JsonResponse({'status': 1})
    except User.DoesNotExist:
        return JsonResponse({'status': 0})


# 登出
def logout_view(request):
    # 登出
    logout(request)
    request.session.flush()     # 清空session
    return redirect('index')


# 首页
# @login_required(login_url='login')    # 如果未登录，将重定向到'login'命名的URL
def index_view(request):
    if request.user.is_authenticated:
        user = request.user
        return render(request, 'index.html', {'user': user})
    return render(request, 'index.html')


# 获取boss信息
def get_boss_info(request):
    # 构建数据集
    job_types = list(JobInfo.objects.values_list('type', flat=True).distinct())
    job_data = list(JobInfo.objects.all().values('type', 'salary'))
    # 构建字典，初始化数据 type: [0-10k, 10-20k, 20-30k, 30-40k, >40k]
    data = {type: [0, 0, 0, 0, 0] for type in job_types}
    for item in job_data:
        min_salary, max_salary = ast.literal_eval(item['salary'])
        avg_salary = (min_salary + max_salary) / 2
        for type in list(data.keys()):
            if item['type'] == type:
                if avg_salary <= 10000:
                    data[type][0] += 1
                elif avg_salary <= 20000:
                    data[type][1] += 1
                elif avg_salary <= 30000:
                    data[type][2] += 1
                elif avg_salary <= 40000:
                    data[type][3] += 1
                else:
                    data[type][4] += 1

    return JsonResponse(data)


# page1
def page1_view(request):
    return render(request, 'page1.html')


def page2_view(request):
    return render(request, 'page2.html')

def page3_view(request):
    return render(request, 'page3.html')


# 编写后端接口，以供前端vue3.js使用
class ItemViewSet(viewsets.ModelViewSet):
    queryset = BossInfo.objects.all()
    serializer_class = ItemSerializer


